package com.sky.service.admin.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.dto.SetmealDTO;
import com.sky.entity.Category;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.mapper.admin.SetMealDishMapper;
import com.sky.mapper.admin.SetmealMapper;
import com.sky.result.Result;
import com.sky.service.admin.CategoryService;
import com.sky.service.admin.DishService;
import com.sky.service.admin.SetmealService;
import com.sky.vo.SetmealVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RequiredArgsConstructor
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    private final SetmealMapper setmealMapper;
    private final DishService dishService;
    private final CategoryService categoryService;
    private final SetMealDishMapper setmealDishMapper;
    private final SetMealDishMapper setMealDishMapper;

    @Override
    public Map<String, Object> findAllPage(Integer categoryId, String name, Integer page,
                                           Integer pageSize, Integer status) {
        Page<Setmeal> setmeslPage = new Page<>();
        setmeslPage.setCurrent(page);
        setmeslPage.setSize(pageSize);

        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(categoryId != null, "category_id", categoryId)
                .like(name != null && !name.isEmpty(), "name", name)
                .eq(status != null, "status", status);
        Page<Setmeal> dishPage1 = setmealMapper.selectPage(setmeslPage, queryWrapper);

        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("total", dishPage1.getTotal());
        stringObjectHashMap.put("records", dishPage1.getRecords());
        return stringObjectHashMap;
    }

    /**
     * 添加套餐
     * @param setmealVO
     */
    @Override
    @Transactional
    @CacheEvict(value = "setmeal", key = "'list:' + #setmealVO.categoryId", condition = "#setmealVO.categoryId != null" )
    public void addSetmeal(SetmealVO setmealVO) {
        Result<Setmeal> setmealResult = new Result<>();
        if (setmealVO.getSetmealDishes() == null){
            setmealResult.setMsg("套餐内没有菜品");
        }
        Category category = categoryService.getById(setmealVO.getCategoryId());
        if (category == null) {
            setmealResult.setMsg("分类不存在");
        }
        setmealVO.setCategoryName(category.getName());
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealVO, setmeal);
        log.info("添加:{}",setmeal);
        setmeal.setStatus(1);
        try {
            setmealMapper.insert(setmeal);
        }catch (Exception e){
            setmealResult.setMsg("添加失败");
        }
        try {
            setmealVO.getSetmealDishes().forEach(setmealDish -> {
                setmealDish.setSetmealId(setmeal.getId());
            });
            setmealDishMapper.insert(setmealVO.getSetmealDishes());
        }catch (Exception e){
            setmealResult.setMsg("添加失败");
        }
    }

    @Override
    public SetmealVO finById(Integer id) {
        if (id == null){
            throw new RuntimeException("id不能为空");
        }
        Setmeal setmeal = setmealMapper.selectById(id);
        List<SetmealDish> setmealDishes = setmealDishMapper.selectList(new QueryWrapper<SetmealDish>()
                                                        .eq("setmeal_id", id));
        SetmealVO setmealVO = new SetmealVO();
        BeanUtils.copyProperties(setmeal, setmealVO);
        setmealVO.setSetmealDishes(setmealDishes);
        return setmealVO;
    }

    /**
     * 修改套餐
     * @param setmealDTO
     */
    @Override
    @Transactional
    @Caching(evict = {
            @CacheEvict(value = "setmeal", key = "'list:' + #setmealDTO.categoryId", condition = "#setmealDTO.categoryId != null" ),
            @CacheEvict(value = "dish_by_setmeal_id", key = "'list:' + #setmealDTO.categoryId", condition = "#setmealDTO.categoryId != null" )
    })
    public void updateSetmeal(SetmealDTO setmealDTO) {
        if (setmealDTO.getId() == null){
            throw new RuntimeException("id不能为空");
        }
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
//        setmeal.setUpdateTime(LocalDateTime.now());
        try {
            setmealMapper.updateById(setmeal);
            setMealDishMapper.updateById(setmealDTO.getSetmealDishes());
        }catch (Exception e){
            throw new RuntimeException("更新错误");
        }
    }


}
